﻿using MediatR;
using Medical.Api.Read.Application.Command.RecyclingCleaning.Disinfects;
using Medical.Api.Read.Dto.RecyclingCleaning.disinfects;
using Medical.Domain.DepartmentInfo;
using Medical.Domain.Enum;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Read.Application.Handler.RecyclingCleaning.Disinfects
{
    /// <summary>
    /// 获取已清洗物品信息的命令处理程序
    /// </summary>
    public class GetCleanedItemCommandHandlter : IRequestHandler<GetCleanedItemCommand, ApiResult<List<CleanedDtos>>>
    {
        /// <summary>
        /// 清洗注册仓储
        /// </summary>
        private readonly IBaseRepository<CleaningRegistration> cleaningRegistrationRep;
        
        /// <summary>
        /// 回收注册仓储
        /// </summary>
        private readonly IBaseRepository<InstrumentRecovery> instrumentRecoveryRep;
        
        /// <summary>
        /// 物资信息仓储
        /// </summary>
        private readonly IBaseRepository<ItemTable> itemTableRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cleaningRegistrationRep">清洗注册仓储</param>
        /// <param name="instrumentRecoveryRep">回收注册仓储</param>
        /// <param name="itemTableRep">物资信息仓储</param>
        public GetCleanedItemCommandHandlter(
            IBaseRepository<CleaningRegistration> cleaningRegistrationRep, 
            IBaseRepository<InstrumentRecovery> instrumentRecoveryRep, 
            IBaseRepository<ItemTable> itemTableRep)
        {
            this.cleaningRegistrationRep = cleaningRegistrationRep;
            this.instrumentRecoveryRep = instrumentRecoveryRep;
            this.itemTableRep = itemTableRep;
        }

        /// <summary>
        /// 处理获取已清洗物品信息的请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>已清洗物品信息列表</returns>
        public async Task<ApiResult<List<CleanedDtos>>> Handle(GetCleanedItemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 定义结果集合
                List<CleanedDtos> cleanedItems = new List<CleanedDtos>();
                
                // 1. 获取已完成清洗的清洗记录
                var cleaningRegistrations = cleaningRegistrationRep.GetAll()
                    .Where(x => !x.IsDeleted && x.CleaningState == RecoveryStatusEnum.已完成)
                    .ToList();
                
                // 如果没有找到已完成的清洗记录，则返回失败结果
                if (cleaningRegistrations == null || !cleaningRegistrations.Any())
                {
                    return new ApiResult<List<CleanedDtos>>
                    {
                        Code = ApiEnums.Fail,
                        Data = null,
                        Msg = "未找到已完成清洗的记录"
                    };
                }
                
                // 2. 收集所有清洗记录中的物品ID
                List<int> recoveryIds = new List<int>();
                foreach (var registration in cleaningRegistrations)
                {
                    if (registration.ItemIds != null && registration.ItemIds.Any())
                    {
                        recoveryIds.AddRange(registration.ItemIds);
                    }
                }
                
                // 如果没有清洗记录物品ID，则返回失败结果
                if (!recoveryIds.Any())
                {
                    return new ApiResult<List<CleanedDtos>>
                    {
                        Code = ApiEnums.Fail,
                        Data = null,
                        Msg = "清洗记录中没有物品信息"
                    };
                }
                
                // 3. 获取回收记录，获取物资包ID
                var recoveryItems = instrumentRecoveryRep.GetAll()
                    .Where(x => recoveryIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();
                
                // 如果没有找到回收记录，则返回失败结果
                if (recoveryItems == null || !recoveryItems.Any())
                {
                    return new ApiResult<List<CleanedDtos>>
                    {
                        Code = ApiEnums.Fail,
                        Data = null,
                        Msg = "未找到相关回收记录"
                    };
                }
                
                // 4. 收集所有回收记录中的物资包ID
                List<int> itemIds = new List<int>();
                foreach (var recovery in recoveryItems)
                {
                    if (recovery.EquipmentPackageId != null && recovery.EquipmentPackageId.Any())
                    {
                        itemIds.AddRange(recovery.EquipmentPackageId);
                    }
                }
                
                // 如果没有物资ID，则返回失败结果
                if (!itemIds.Any())
                {
                    return new ApiResult<List<CleanedDtos>>
                    {
                        Code = ApiEnums.Fail,
                        Data = null,
                        Msg = "回收记录中没有物资信息"
                    };
                }
                
                // 5. 查询物资信息
                var items = itemTableRep.GetAll()
                    .Where(x => itemIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();
                
                // 如果没有找到物资信息，则返回失败结果
                if (items == null || !items.Any())
                {
                    return new ApiResult<List<CleanedDtos>>
                    {
                        Code = ApiEnums.Fail,
                        Data = null,
                        Msg = "未找到相关物资信息"
                    };
                }
                
                // 6. 转换为DTO对象
                foreach (var item in items)
                {
                    cleanedItems.Add(new CleanedDtos
                    {
                        Id = item.Id,
                        CleaningTime = item.CreateTime,
                        ItemCode = item.ItemCode,
                        ItemName = item.ItemName,
                        UsingDepartment = "内科", // 此处使用固定科室，后续可优化为从相关数据获取
                    });
                }
                
                // 7. 返回成功结果
                return new ApiResult<List<CleanedDtos>>
                {
                    Code = ApiEnums.Success,
                    Data = cleanedItems,
                    Msg = "获取已清洗物品信息成功"
                };
            }
            catch (Exception ex)
            {
                // 8. 处理异常情况
                return new ApiResult<List<CleanedDtos>>
                {
                    Code = ApiEnums.Fail,
                    Data = null,
                    Msg = $"获取已清洗物品信息失败: {ex.Message}"
                };
            }
        }
    }
}
